var catew = $('.fisrstnav').width()-150;
var cateLiw = 0;
var marginLen=0,marginWidth=0;

//1为编辑 0为add
var addOredit=0;
//分页
var totalRecords_pagerContant=0, //总条数
    pageIndex_pagerContant=1  // 当前页码
;
let dataJson={
    pageIndex:pageIndex_pagerContant,
    pageSize:10
};
var path_name=window.location.pathname
//编辑器
var editor;
//
let data_knowledge='';
(function () {
    // 获取知识条目
    getKnow()

    // 编辑器初始化
    editor = new FroalaEditor('#editor',
        ({
            placeholderText: '',
            charCounterCount: true,//默认 显示字数
            saveInterval: 0,//不自动保存，默认10000，0为不自动保存
            toolbarBottom: false,//默认
            toolbarInline: false,//true选中设置样式,默认false
            imageUploadMethod: 'POST',
            heightMin: 300,
            charCounterMax: 3000,  //最大字数限制，-1为不限制
            // saveURL: '/NewsController/addNotify',  //自动保存的地址（body参数为html内容）
            saveURL: '/knowledgeSection/addKnSection',  //自动保存的地址（body参数为html内容）

            saveParams: {postId: '1'},  //保存内容时传的参数
            spellcheck: false,  //是否允许浏览器对输入内容进行拼写检查
            imageUploadURL: '/file/uploadByOneFileEdit',//上传到本地服务器
            videoUploadURL: '/file/uploadByOneFileEdit',
            imageDefaultWidth: 1300,
            imageResizeWithPercent: true,
            autoHeightEnabled:true,
            language: 'zh_cn',

        }));





})()

//获取知识条目 初始化
function getKnow() {
    knowledgeAjaxGet('/knowledgeItem/selectKnItemList').then((res) => {


        if (res.code == '000000') {
            data_knowledge=res.data
            //初始化知识条目
            let htmlLi=''
            if(path_name=='/front/productManager/knowledgeItem' && ifAdmin){
                for(let i=0,len=data_knowledge.length;i<len;i++){
                    htmlLi+=`<li data-know-id="${data_knowledge[i].knowledgeItemId}"><span>${data_knowledge[i].knowledgeItemName}</span>
                              <span class="mt-close-tab mdi mdi-close mdi-close-item"></span>
                    </li>`
                }
            }else{
                for(let i=0,len=data_knowledge.length;i<len;i++){
                    htmlLi+=`<li data-know-id="${data_knowledge[i].knowledgeItemId}"><span>${data_knowledge[i].knowledgeItemName}</span>
                              
                    </li>`
                }
            }


            $(".fisrstnav ul").html(htmlLi)
            $(".fisrstnav ul li").eq(0).addClass('liactive')

            delItem()

            changeHandelKnowHead() //知识条目切换
            if(path_name=='/front/productManager/knowledgeItem' && ifAdmin){
                dblClick() //编辑文章头目
            }

            //根据ID查询知识章节接口
            // dataJson={
            //     itemId:$(".fisrstnav ul li").eq(0).attr("data-know-id"),
            //     pageIndex:1,
            //     pageSize:10
            // }
            dataJson.itemId=$(".fisrstnav ul li").eq(0).attr("data-know-id")
            if($(".fisrstnav ul li").eq(0).attr("data-know-id")!=undefined){
                knowFunAjax(dataJson) //文章 初始化
            }



//按钮箭头


            $('.fisrstnav ul li').each(function(){
                cateLiw +=$(this).outerWidth();
            })
            if(cateLiw<catew){

                $('.next').hide();
            }


        } else {

            // console.log(res.msg)

        }
    })
}

//删除条目
function delItem() {
//点击删除
    $(".mdi-close-item").click(function () {
        if($(".fisrstnav ul li").length<2){
            $.alert("知识条目不能少于1条")
            return;
        }
        event.stopPropagation();
        //    /knowledgeItem/delKnItemById/{itemId}
        //    itemId
        var urldelItem='/knowledgeItem/delKnItemById/'+$(this).parent().attr("data-know-id")

        knowledgeAjaxGet(urldelItem).then((res)=>{
            $.alert({
                title: '提示',
                content: '删除成功！',
                buttons: {
                    confirm: {
                        text: '确认',
                        btnClass: 'btn-primary',
                        action: function () {

                            window.location.reload();

                        }
                    }
                }
            });
        })

    })
}


//点击知识条目切换

function changeHandelKnowHead(){
    $(".fisrstnav ul li").click(function () {
        $(this).addClass('liactive')
        $(this).siblings().removeClass("liactive")
        dataJson.itemId=$(this).attr("data-know-id")
        knowFunAjax(dataJson) //文章




    })
}

//文章初始化
function knowFunAjax(dataJson) {
    knowledgeAjaxPost('/knowledgeSection/selectKnSectionList',dataJson,'application/x-www-form-urlencoded; charset=UTF-8').then((res)=>{
        if (res.code == '000000'){
            let htmlDiv=''
            if(path_name=='/front/productManager/knowledgeItem' && ifAdmin){
                for(let i=0,len=res.data.length;i<len;i++){
                    htmlDiv+=`<div class="cont-over" data-name-id="${res.data[i].sectionId}">
                                <p class="article-paragraph">第${i+1+(res.pageIndex-1)*10}章<span title="${res.data[i].sectionName}">${res.data[i].sectionName}</span> <span class="mt-close-tab mdi mdi-close mdi-close-content" style="padding:0"></span> </p>  
                             <p class="cont-right"></p></div>`
                }
            }else{
                for(let i=0,len=res.data.length;i<len;i++){
                    htmlDiv+=`<div class="cont-over" data-name-id="${res.data[i].sectionId}">
                                <p class="article-paragraph">第${i+1+(res.pageIndex-1)*10}章<span title="${res.data[i].sectionName}">${res.data[i].sectionName}</span> </p>  
                             <p class="cont-right"></p></div>`
                }
            }

            $(".conactive").html(htmlDiv)
            articleHandleClick()
            totalRecords_pagerContant=res.totalRecords
            if(path_name=='/front/productManager/knowledgeItem' && ifAdmin){
                dbClickChapter()
            }

            pageRight()


            hoverActicle()

            delSection()





        }else{

        }
        // console.log(res)
    })

}
//w文章划过事件
function hoverActicle() {
    $(".article-paragraph").hover(function () {

        $(this).find('.mdi-close-content').css("display","inline-block")

        $(this).parent().siblings().find('.mdi-close-content').css("display","none")
        $(".blueShow").find('.mdi-close-content').css("display","inline-block")
    })
    $('.mdi-close-content').click(function () {
        $(this).parent().parent().remove()
    })
}

//文章初始化
function knowFunAjax1(dataJson) {
    knowledgeAjaxPost('/knowledgeSection/selectKnSectionList',dataJson,'application/x-www-form-urlencoded; charset=UTF-8').then((res)=>{
        if (res.code == '000000'){
            let htmlDiv=''
            if(path_name=='/front/productManager/knowledgeItem' && ifAdmin){
                for(let i=0,len=res.data.length;i<len;i++){
                    htmlDiv+=`<div class="cont-over" data-name-id="${res.data[i].sectionId}">
                                <p class="article-paragraph">第${i+1+(res.pageIndex-1)*10}章<span title="${res.data[i].sectionName}">${res.data[i].sectionName}</span> <span class="mt-close-tab mdi mdi-close mdi-close-content" style="padding:0"></span> </p>  
                             <p class="cont-right"></p></div>`
                }
            }else{
                for(let i=0,len=res.data.length;i<len;i++){
                    htmlDiv+=`<div class="cont-over" data-name-id="${res.data[i].sectionId}">
                                <p class="article-paragraph">第${i+1+(res.pageIndex-1)*10}章<span title="${res.data[i].sectionName}">${res.data[i].sectionName}</span> </p>  
                             <p class="cont-right"></p></div>`
                }
            }

            $(".conactive").html(htmlDiv)
            articleHandleClick()
            totalRecords_pagerContant=res.totalRecords
            if(path_name=='/front/productManager/knowledgeItem' && ifAdmin){
                dbClickChapter()
            }


            hoverActicle()

            delSection()






        }else{

        }
        // console.log(res)
    })

}


//删除文章

function delSection() {
    $(".mdi-close-content").click(function () {
        event.stopPropagation();
        //    /knowledgeItem/delKnItemById/{itemId}
        //    itemId
        var urldel='/knowledgeSection/delKnSectionById/'+$(this).parent().parent().attr("data-name-id")

        knowledgeAjaxGet(urldel).then((res)=>{
            $.alert({
                title: '提示',
                content: '删除成功！',
                buttons: {
                    confirm: {
                        text: '确认',
                        btnClass: 'btn-primary',
                        action: function () {

                            // window.location.reload();

                        }
                    }
                }
            });
            knowFunAjax1(dataJson)
            pageRight()
        })

    })

}







//上
function prevFun() {
    if(marginWidth!=0){
        $(".fisrstnav ul").css({
            'margin-left':0
        })
    }
}
//下

//点击确定是 add添加 知识条目
function sureBtnAdd() {
    $('#Addform').bootstrapValidator({
        fields: {
            tabName: {
                validators: {
                    notEmpty: {
                        message: '知识类目名称'
                    }
                }
            },

        },
    })
    $("#Addform").bootstrapValidator('validate');//提交验证
    if (!$("#Addform").data('bootstrapValidator').isValid()) {//获取验证结果，如果成功，执行下面代码

        return;
    }

    let addData={
        knItemName:$("#tabName").val()
    }

    knowledgeAjaxPost('/knowledgeItem/addKnItem',JSON.stringify(addData),'application/json;charset=utf-8').then((res)=>{
        if (res.code == '000000'){

            $(".fisrstnav ul li").removeClass('liactive')
            var li=''
                if(path_name=='/front/productManager/knowledgeItem' && ifAdmin){
                    //data-know-id="${data_knowledge[i].knowledgeItemId}"
                    li = `<li class="liactive" data-know-id="${res.data}"><span>${addData.knItemName}</span><span class="mt-close-tab mdi mdi-close mdi-close-item"></span></li>`;
                }else{
                    li = `<li class="liactive" data-know-id="${res.data}"><span>${addData.knItemName}</span></li>`;
                }

            $(".fisrstnav ul").append(li)

            cateLiw=0
            $('.fisrstnav ul li').each(function(){
                cateLiw +=($(this).outerWidth()+20);
            })

            if(cateLiw<660){
                $(".fisrstnav ul").css({
                    'margin-left':0+'px'
                })
            }else{
                cateLiw=cateLiw-660
                $(".fisrstnav ul").css({
                    'margin-left':-(cateLiw )+'px'
                })
            }



            $('.prev').show();

            $("#tabAdd").modal('hide')
            dblClick() //双击条目
            delItem()
            changeHandelKnowHead() //知识条目切换
            $("#Addform").load(location.href+" #Addform");
        }
    })



}
//双击条目
function dblClick() {
    for (var i = 0; i < $(".fisrstnav ul li").length; i++) {
        $(".fisrstnav ul li").eq(i).dblclick(function () {
            var str = $(this).children().eq(0).html();
            var data_item_id=$(this).attr('data-know-id')
            $(this).children().eq(0).html('<input type="text" maxlength="15"/>')
            // this.innerHTML = '<input type="text" />';
            var input = $(this).children().eq(0).children();
            input.val(str);
            input.select(); // 文本框里面的文字处于选定状态

            input.blur(function () {
                var that=this
                if($(that).val()!=""){
                    //解决选项卡内容为空之后不能再改的问题
                    $(that).parent().html($(that).val())
                    let data={
                        knItemId:data_item_id,
                        knItemName:$(that).val()
                    }
                    knowledgeAjaxPost('/knowledgeItem/updateKnItem',JSON.stringify(data),'application/json;charset=utf-8').then((res)=>{

                    })
                }


            })




        })
    }
}



// //按钮箭头
// var catew = $('.fisrstnav').width()-150;
// var cateLiw = 0;
// $('.fisrstnav ul li').each(function(){
//     cateLiw +=$(this).outerWidth();
// })
// if(cateLiw<catew){
//
//     // $('.next').hide();
// }
var i =0;
$('.next').click(function(){
    $('.fisrstnav ul').animate({
        "margin-left":-(catew*(i+1))+'px'
    },500)
    i++;
    if((catew+150)*(i)+(catew+150)>=cateLiw){
        $('.prev').show();
        $('.next').hide();
    }
})
$('.prev').click(function(){
    i =0
    $('.fisrstnav ul').animate({
        "margin-left":0+'px'
    },500)
    $(this).hide();$('.next').show();
})

//点击 查询知识章节内容，显示隐藏
function articleHandleClick(){
    $('.cont-right').hide()
    $(".article-paragraph").click(function(){

        // let sectionId={
        //     sectionId:$(this).parent().attr("data-name-id")
        // }
        $(this).addClass("blueShow")
        $(this).parent().siblings().find('.article-paragraph').removeClass("blueShow")
        let urlSplit='/knowledgeSection/selectSectionByKey/'+$(this).parent().attr("data-name-id")
        knowledgeAjaxGet(urlSplit).then((res)=>{
            if (res.code == '000000'){
                $(this).parent().find('.cont-right').html(res.data.sectionContent)
            }

        })


        $(this).parent().find('.cont-right').css("display","inline-block")
        $(this).parent().siblings().find('.cont-right').css("display","none")
    });
}

//分页
function pageRight(){

    setTimeout(function () {
        if(totalRecords_pagerContant==0){
            totalRecords_pagerContant=1
        }
        $("#pagerContant").zPager({
            htmlBox: $('#wraper'),
            btnShow: true,
            ajaxSetData: false,
            minPage:1,//最小页码数，页码小于此数值则不显示上下分页按钮
            totalData: totalRecords_pagerContant, //数据总条数
            pageData: 10, //每页数据条数
            pageCount: 0, //总页数
            current: 1, //当前页码数
            pageStep: 10, //当前可见最多页码个数
            btnShow: false, //是否显示第一页和最后一页按钮


        });
        if($("#pagerContant").children().length==1){
            $("#pagerContant").children().remove()
        }


    },100)


}




function currentPage(currentPage){
    /*
        触发页码数位置： Page/js/jquery.z-pager.js 64行
    */
    // "当前页码数：" + currentPage

    pageIndex_pagerContant=currentPage
    dataJson.pageIndex=currentPage
    knowFunAjax1(dataJson)


}

//add 添加文章 富文本编辑器 编辑文章
function btnTrum() {

    // $("#chapterTitle").val('')
    // $('#customized-buttonpane').trumbowyg('html','')
    $('#trumbowyForm').bootstrapValidator({
        fields: {
            chapterTitle: {
                validators: {
                    notEmpty: {
                        message: '章节名称不能为空'
                    }
                }
            }

        },
    })
    $("#trumbowyForm").bootstrapValidator('validate');//提交验证
    if (!$("#trumbowyForm").data('bootstrapValidator').isValid()) {//获取验证结果，如果成功，执行下面代码
        // if($('#editor .fr-view').html()=='<p><br></p>' || $('#editor .fr-view').html()==''){
        //     $(".redvalidators").show()
        //     return;
        // }

        return;
    }
    // if($('#editor .fr-view').html()=='<p><br></p>' || $('#editor .fr-view').html()==''){
    //     $(".redvalidators").show()
    //     return;
    // }


    $("#trumbowyg").modal('hide')

//    /knowledgeSection/addKnSection


//    添加知识章节
    if(addOredit==0){
        let dataAdd={
            "knowledgeItemId":$(".liactive").attr("data-know-id"),
            "sectionName":$("#chapterTitle").val(),
            "sectionContent":$('#editor .fr-view').html()
            //$('#editor .fr-view').html()
            //    $('#customized-buttonpane').trumbowyg('html')
            //    editor.html.insert($('#content').text())
        }
        knowledgeAjaxPost('/knowledgeSection/addKnSection',JSON.stringify(dataAdd),'application/json;charset=utf-8').then((res)=>{

            if(res.code=='000000'){
                knowFunAjax1(dataJson)
                pageRight()
            }
        })
    }else{
        //    编辑知识章节
        let dataChange={
            "sectionId":$(".blueShow").parent().attr("data-name-id"),
            "sectionName":$("#chapterTitle").val(),
            "sectionContent":$('#editor .fr-view').html()
            //$('#editor .fr-view').html()
            //    $('#customized-buttonpane').trumbowyg('html')
            //    editor.html.insert($('#content').text())
        }
        knowledgeAjaxPost('/knowledgeSection/updateKnSection',JSON.stringify(dataChange),'application/json;charset=utf-8').then((res)=>{

            if(res.code=='000000'){
                knowFunAjax1(dataJson)
            }
        })
    }




}

$('#trumbowyg').on('hidden.bs.modal', function (){

    $(this).find('form')[0].reset()
    // editor.html.insert();
    $('#editor .fr-view').html('')
    if($("#trumbowyForm").data('bootstrapValidator')!=undefined){
        $("#trumbowyForm").data('bootstrapValidator').destroy();
        $('#trumbowyForm').data('bootstrapValidator', null);
    }


});


//点击add文章
$(".btn-section").click(function () {
    addOredit=0
})

//双击事件 文章
function dbClickChapter() {
    $(".article-paragraph").dblclick(function () {
        addOredit=1
        $("#trumbowyg").modal('show')

        $("#chapterTitle").val($(this).find('span').html())
        // $('#customized-buttonpane').trumbowyg('html',$(this).siblings().html())
        editor.html.insert($(this).siblings().html());
    })
}

//富文本框的事件
function show_element(e) {
    if($('#editor .fr-view').html()!=''){

        $(".redvalidators").hide()
        $("#sureSubmit").attr("disabled",false)
    }
}


















//封装ajax

//    获取知识条目
function knowledgeAjaxGet(url) {
    var promise=new Promise((resolve, reject)=>{
        $.ajax({
            type: 'get',
            url: url,
            // data: data,
            dataType: 'json',
            success: function (res) {
                resolve(res)
            },
            error: function (res) {
                reject(res)

            }
        });
    })
    promise.catch(function(error) {
        $.alert(error.message)

    });

    return promise

}

function knowledgeAjaxPost(url,data,contentType) {
    // contentType: "application/json;charset=utf-8",
    var promises=new Promise((resolve, reject)=>{
        $.ajax({
            type: 'post',
            url: url,
            data: data,
            contentType:contentType,
            dataType: 'json',
            success: function (res) {
                resolve(res)
                if(res.code!='000000'){
                    $.alert(res.data)
                }
            },
            error: function (res) {
                reject(res)
                $.alert(res.data)
            }
        });
    })

    promises.catch(function(error) {
        $.alert(error.message)
    });

    return promises

}